<?php

class addInsuranceAttendAction extends baseTLUBenefitsAction
{
    private $insuranceAttendService;

    /**
     * @param InsuranceAttendService $insuranceAttendService
     */
    public function setInsuranceAttendService(InsuranceAttendService $insuranceAttendService)
    {
        $this->insuranceAttendService = $insuranceAttendService;
    }

    /**
     * @return InsuranceAttendService
     */
    public function getInsuranceAttendService()
    {
        if (is_null($this->insuranceAttendService)) {
            $this->insuranceAttendService = new InsuranceAttendService();
            $this->insuranceAttendService->setInsuranceAttendDao(new InsuranceAttendDao());
        }
        return $this->insuranceAttendService;
    }

    /**
     * @param sfForm $form
     * @return
     */
    public function setForm(sfForm $form)
    {
        if (is_null($this->form)) {
            $this->form = $form;
        }
    }

    public function getForm()
    {
        $this->form->request = $this->getRequest();
        return $this->form;
    }

    public function execute($request)
    {
        /* For highlighting corresponding menu item */
        $request->setParameter('initialActionName', 'viewInsuranceAttend');

        $usrObj = $this->getUser()->getAttribute('user');
        if (!$usrObj->isAdmin()) {
            $this->redirect('benefits/viewInsuranceAttend');
        }

        $this->insuranceAttendId = $request->getParameter('Id');
        $values = array('insuranceAttendId' => $this->insuranceAttendId);
        $this->setForm(new InsuranceAttendForm(array(), $values));

        if ($this->getUser()->hasFlash('templateMessage')) {
            list($this->messageType, $this->message) = $this->getUser()->getFlash('templateMessage');
            MessageRegistry::instance()->addMessage($this->message, 'benefits', 'addInsuranceAttend', MessageRegistry::PREPEND);
            $this->message = MessageRegistry::instance()->getMessage('benefits', 'addInsuranceAttend');
        }

        if ($request->isMethod('post')) {

            $this->form->bind($request->getParameter($this->form->getName()));
            if ($this->form->isValid()) {
                $this->insuranceAttendId = $this->form->save();
                $this->getUser()->setFlash('success', __(TopLevelMessages::SAVE_SUCCESS));
                $this->redirect('benefits/addInsuranceAttend?Id=' . $this->insuranceAttendId);
            }
        }
    }
}